﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace YTSK.FrmList
{
    public partial class FrmSKList : Form
    {


        #region 初始化
        public FrmSKList()
        {
            try
            {
                InitializeComponent();
                this.Icon = YTSK.Properties.Resources.Fly;
                this.Text = string.Format("已开发票列表---版本{0}-{1}-{2}",
                    ServerConfig.Version.ToString("yyyyMMdd"), ServerConfig._company, ServerConfig.UserName);
                Common.HandleReport.InitControl(this, this.dataGridView1, "v_sk_salebill");
                this.dataGridView1.CellMouseDoubleClick += dataGridView1_MouseDoubleClick;
                this.Resize += frmMain_Resize;
                foreach (ToolStripItem bar in this.toolStrip1.Items)
                {
                    if (bar.Text.Length > 0)
                    { bar.Click += toolbar_click; }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 双击事件
        public void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                var row = this.dataGridView1.CurrentRow;
                if (row == null) { return; }
                var obj = row.Cells["ID"].Value.ObjToInt();
                if (obj != 0)
                {
                    var f = new FrmKP.FrmSK();
                    f.Show();
                    f.Reflesh(obj);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion



        #region 全选
        private bool _bSel = true;
        private void SelectAll(object sender, EventArgs e)
        {
            var dg = this.dataGridView1;
            for (int i = 0; i < dg.Rows.Count; i++)
            {
                var row = dg.Rows[i];
                row.Cells["selcol"].Value = _bSel ? "√" : (row.Index + 1).ToString();
            }
            _bSel = !_bSel;
        }

        #endregion

        #region 窗体大小
        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (this.Width >40)
            { this.dataGridView1.Width = this.Width - 40; }
            if (this.Height > 200)
            {
                this.dataGridView1.Height = this.Height - 200;
            }
        }
        #endregion


        #region 工具栏事件
        public void toolbar_click(object sender, EventArgs e)
        {
            if (sender.GetType() != typeof(ToolStripButton)) { return; }
            var bt = (ToolStripButton)sender;
            var text = bt.Text;
            switch (text)
            {
                case "导出":
                    Common.handleDataGrid.ExportExcel(this.dataGridView1);
                    break;
                case "作废发票":
                    AbandonVouch();
                    break;
                case "恢复作废发票":
                    CancelAbandonVouch();
                    break;
                case "手工红冲发票":
                    RedVouch();
                    break;
                case "云开票红冲":
                    RedFPYKP();
                    break;
                case "修正发票号码":
                    ModifyVouchCode();
                    break;
                case "退出":
                    this.Close();
                    break;
                default:
                    MessageBox.Show("没有找到程序");
                    break;
            }

        }
        #endregion

        #region 作废发票
        public void AbandonVouch()
        {
            try
            {
                var dg = this.dataGridView1;
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { return; }
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var fphm = currentrow.Cells["fphm"].Value.ObjToString();

                var dr = MessageBox.Show(string.Format("确认要作废发票[{0}]么？请先在税控机上作废", fphm), "提示", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No) { return; }
                var url = string.Format("{0}/api/oms/SKSalebillVouch/AbandonVouch?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var pos = new Dictionary<string, object>();
                pos.Add("ID", _id);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }

                if (result.result != 1) { MessageBox.Show("作废发票出错:" + result.resultdetail); return; }
                MessageBox.Show("作废发票成功!");
                #region 显示数据
                GetData();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 恢复作废发票
        public void CancelAbandonVouch()
        {
            try
            {
                var dg = this.dataGridView1;
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { return; }
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var fphm = currentrow.Cells["fphm"].Value.ObjToString();

                var dr = MessageBox.Show(string.Format("确认要恢复作废发票[{0}]么？", fphm), "提示", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No) { return; }
                var url = string.Format("{0}/api/oms/SKSalebillVouch/CancelAbandonVouch?token={1}",
                        ServerConfig.ServerAddress, ServerConfig.GetToken());
                var pos = new Dictionary<string, object>();
                pos.Add("ID", _id);
                var s = Common.handleHttp.Post(pos, url);
                var result = Common.handleJSON.DeserializeResult(s);
                if (result.result == -1 || result.result == 1002)
                {
                    MessageBox.Show(result.resultdetail); return;
                }

                if (result.result != 1) { MessageBox.Show("恢复作废发票出错:" + result.resultdetail); return; }
                MessageBox.Show("恢复发票成功!");
                #region 显示数据
                GetData();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 红冲发票-手工输入发票号码
        public void RedVouch()
        {
            try
            {
                var dg = this.dataGridView1;
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { return; }
                var id = currentrow.Cells["ID"].Value.ObjToInt();
                var fphm = currentrow.Cells["fphm"].Value.ObjToString();
                var dr = MessageBox.Show(string.Format("确认要红冲发票[{0}]么？请先在税控机上红冲，然后输入新的发票", fphm), "提示", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No) { return; }
                var ddate = DateTime.Now;
                var f = new FrmKP.FrmReturn_SK_Red(id);
                f.ShowDialog();
                GetData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 云开票红冲
        /// <summary>
        /// 云开票红冲
        /// </summary>
        public void RedFPYKP()
        {
            var dg = this.dataGridView1;
            var currentrow = dg.CurrentRow;
            if (currentrow == null) { return; }
            var id = currentrow.Cells["ID"].Value.ObjToInt();

            var url = string.Format("{0}/api/oms/Rd2SK/SetWebRed?token={1}&id={2}",
                ServerConfig.ServerAddress, ServerConfig.GetToken(), id);
            var s = Common.handleHttp.Get(url);
            var result = Common.handleJSON.DeserializeResult(s);
            if (result.result == -1 || result.result == 1002)
            {
                var errmsg = result.resultdetail;
                errmsg= System.Web.HttpUtility.UrlDecode(errmsg);
                var ferr = new FrmMessage();
                ferr.ShowMsg(false, "错误", errmsg);
                return;
            }
            var sk_red = ((Dictionary<string, object>)result.GetVal("skmain")).ToObj<Model.SK_SalebillVouch>();


            var ftip = new FrmTip();
            ftip.Show();
            var isecond = 0;
            while (isecond < 20)
            {
                ftip.setValue("电子发票红冲请求已经发送，正在等待开票结果，请稍侯...", isecond);
                System.Threading.Thread.Sleep(500);
                isecond++;
            }
            ftip.Close();
            url = string.Format("{0}/api/oms/Rd2SK/GetFPStatusSK?token={1}&id={2}",
            ServerConfig.ServerAddress, ServerConfig.GetToken(), sk_red.ID);
            s = Common.handleHttp.Get(url);
            result = Common.handleJSON.DeserializeResult(s);
            if (result.result != 1) 
            {
                var fmsg = new FrmMessage();
                var errmsg = result.resultdetail;
                errmsg = System.Web.HttpUtility.UrlDecode(errmsg);
                fmsg.ShowMsg(true, "红冲发票排队中", errmsg);
            }
            else
            {
                var fmsg = new FrmMessage();
                fmsg.ShowMsg(true, "红冲发票成功", result.resultdetail);
            }
            return;
        }
        #endregion

        #region 修正发票号码
        public virtual void ModifyVouchCode()
        {
            try
            {
                var dg = this.dataGridView1;
                var currentrow = dg.CurrentRow;
                if (currentrow == null) { return; }
                var _id = currentrow.Cells["ID"].Value.ObjToInt();
                var fphm = currentrow.Cells["fphm"].Value.ObjToString();
                var fpdm = currentrow.Cells["fpdm"].Value.ObjToString();
                var ddate = currentrow.Cells["dDate"].Value.ObjToDate();
                var f = new FrmKP.FrmReturn_SK_FPHM(_id, fpdm, fphm, ddate);
                f.ShowDialog();
                #region 显示数据
                GetData();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        #endregion

        #region 报表数据
        private void btQuery_Click(object sender, EventArgs e)
        {
            GetData();
        }
        /// <summary>
        /// 报表数据获取
        /// </summary>
        private void GetData()
        {
            Common.HandleReport.GetGridData(this.groupBox2, this.dataGridView1, "v_sk_salebill");
            Common.cDataGrid.DoubleBuffered(this.dataGridView1, true);
        }
        #endregion 



    }
}
